<?php
/**
 * Created by PhpStorm
 * author: bxm
 * Date: 2023/3/10
 * Time: 14:07
 */

namespace app\admin\controller;

use app\common\controller\AdminController;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
class Upload extends AdminController
{
//{
//"code": 0
//,"msg": ""
//,"data": {
//"src": "http://cdn.layui.com/123.jpg"
//}
//}
public function upload()
    {

        if ($this->request->isPost()) {
            $file = $this->request->file('file');
            if (empty($file)) {

                echo '请选择上传文件';exit;

            }
//            var_dump($file);exit;
            $tmp_name = $file->getOriginalName();
            $fileExt = $file->getOriginalExtension();
            $fileType = $file->getOriginalMime();
            $fileSize = $file->getSize();
            $path = $file->getRealPath();//获取临时文件存放的目录，然后通过file_get_content($path)获取到文件对象，
            $up_dir = ROOT_PATH . 'public'.DS.'excel'.DS.'file'.DS.date('Ymd');    //分片合并存放目录
            if (!file_exists($up_dir)) {
                mkdir($up_dir, 0777, true); //不存在创建文件夹
                chmod($up_dir, 0777); //强制赋予权限
            }
            $file_name =  $up_dir . DS . date('YmdHis', time()) . '.' . $fileExt;

            move_uploaded_file($path,  $file_name);
            $reader      = IOFactory::createReader('Xlsx');
            $spreadsheet = $reader->load($file_name);
            $sheet       = $spreadsheet->getActiveSheet();
            $highest     = $sheet->getHighestColumn();
            $row         = $sheet->getHighestRow();
            $data        = [];
            for ($i = 2; $i <= $row; $i++) {
                $data[] = trim($sheet->getCellByColumnAndRow(1, $i)->getValue());


            }
            echo  json_encode(['code'=>0,'msg'=>'上传成功','data'=>$data]);

        }
    }
}